import { map } from 'rxjs';
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { DialogService, EditableTip, FormLayout, TableWidthConfig } from 'ng-devui';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { MaterialService } from 'src/app/@core/services/material/material.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { GetPartsComponent } from 'src/app/pages/product/product-job-pink/add-picking-list/select-part/get-parts/get-parts.component';
import { SelectReturnMaterialJoberComponent } from '../select-return-material-jober/select-return-material-jober.component';
import { SelectStorehouseComponent } from 'src/app/@shared/components/select-storehouse/select-storehouse.component';
import { SelectPositionComponent } from 'src/app/@shared/components/select-position/select-position.component';

@Component({
  selector: 'app-add-returning-materials-to-production',
  templateUrl: './add-returning-materials-to-production.component.html',
  styleUrls: ['./add-returning-materials-to-production.component.scss']
})
export class AddReturningMaterialsToProductionComponent {
  layoutDirection: FormLayout = FormLayout.Horizontal;
  editableTip = EditableTip.hover;

  CreateJobOrderReturn: any = {
    jobOrderReturnId: null,
    jobOrderReturnNum: "",
    creatorName: "",
    createTime: null,
    auditorName: null,
    auditTime: null,
    isReturn: false,
    isAudit: false,
    status:'未开始审核',
    jobOrderReturnDetails: [
      {
        jobOrderReturnDetailId: 0,
        jobOrderReturnId: 0,
        jobOrderId: 0,
        jobNum: "",
        processNumber: 0,
        processId: 0,
        jobOrderProcessId: 0,
        processNum: "",
        processName: "",
        jobOrderProcessPartId: 0,
        partId: 0,
        partNum: "",
        partName: "",
        partType: "",
        partUOM: "",
        returnQuantity: 0,
        returnUnit: "",
        returnWarehouseId: 0,
        warehouseNum: "",
        warehouseName: "",
        returnPositionId: 0,
        positionNum: "",
        positionName: "",
        requirementQuantity: 0,
        defaultWarehouseId: 0,
        defaultWarehouseName: "",
        defaultWarehouseNum: "",
        defaultPositionId: 0,
        defaultPositionName: "",
        defaultPositionNum: "",
        stockQuantity: 0,
        issueQuantity: 0,
        status:'未开始审核'
      }
    ]
  };
  info: any = {}
  dataTableOptions = {
    columns: [
      {
        field: 'name',
        header: '工单号',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '工序名称',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料名称',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '需求数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '已发数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '退料数量',
        fieldType: 'text',
      },

      {
        field: 'name',
        header: '仓库',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '仓位',
        fieldType: 'text',
      },
    ]
  }
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '100px'
    },
    {
      field: '操作',
      width: '100px'
    },
    {
      field: '工单号',
      width: '100px'
    },
    {
      field: '销售订单号',
      width: '100px'
    },
    {
      field: '销售订单号',
      width: '100px'
    },
    {
      field: '产品编码',
      width: '100px'
    },
    {
      field: '规格',
      width: '150px'
    },
    {
      field: '单位',
      width: '150px'
    },
    {
      field: '计划数量',
      width: '150px'
    },

  ];
  msgs: { severity: any; summary: any; content: any; }[];
  constructor(private dialogService: DialogService, private StorehouseService: StorehouseService, private EncodeRulesService: EncodeRulesService, private Router: Router) { }
  submit($event: any) {
    this.CreateJobOrderReturn.createTime = new Date()
    this.CreateJobOrderReturn.jobOrderReturnDetails = this.CreateJobOrderReturn.jobOrderReturnDetails.map((item: any) => ({
      jobOrderReturnDetailId: null,
      jobOrderReturnId: null,
      jobOrderId: item.jobOrderId,
      jobNum:item.jobNum,
      processNumber:item.processNumber,
      processId:item.processId,
      jobOrderProcessId: item.jobOrderProcessId,
      processNum: item.processNum,
      processName: item.processName,
      jobOrderProcessPartId: item.jobOrderProcessPartId,
      partId: item.partId,
      partNum: item.partNum,
      partName: item.partName,
      partType: item.partType,
      partUOM: item.partUOM,
      returnQuantity: item.returnQuantity,
      returnUnit: item.partUOM,
      returnWarehouseId: item.returnWarehouseId,
      warehouseNum: item.warehouseNum,
      warehouseName: item.warehouseName,
      returnPositionId: item.returnPositionId,
      positionNum: item.positionNum,
      positionName: item.positionName,
      requirementQuantity: item.requirementQuantity,
      defaultWarehouseId: item.defaultWarehouseId,
      defaultWarehouseName: item.defaultWarehouseName,
      defaultWarehouseNum: item.defaultWarehouseNum,
      defaultPositionId: item.defaultPositionId,
      defaultPositionName: item.defaultPositionName,
      defaultPositionNum: item.defaultPositionNum,
      stockQuantity: item.stockQuantity,
      issueQuantity: item.issueQuantity,
      status:'未开始审核'
    }));
    this.StorehouseService.CreateJobOrderReturn(this.CreateJobOrderReturn).subscribe((res: any) => {
      this.showToast('success', '成功', '创建成功')
      setTimeout(() => {
        this.Router.navigate(['/pages/inventory/returning-materials-to-production'])
      }, 1000);
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
    )
  }
  cancle() {
    this.Router.navigate(['/pages/inventory/returning-materials-to-production'])
  }
  ngOnInit(): void {
    const info = localStorage.getItem('userinfo');
    this.EncodeRulesService.GenerateWarehouseCodeRule('生产退料单','生产退料单').subscribe((res: any) => {
      this.CreateJobOrderReturn.jobOrderReturnNum = res
    })
    const parsedInfo = JSON.parse(info);
    this.CreateJobOrderReturn.creatorName = parsedInfo.username;
  }
  issuances(dialogtype?: string) {
    const results = this.dialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width: '1000px',
      title: '选择工单工序',
      data: "生产退料单",
      content: SelectReturnMaterialJoberComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            console.log(results.modalContentInstance.getParts)
            if (results.modalContentInstance.getParts) {
              this.StorehouseService.GetReturnJobOrderProcessPartsByProcessId(results.modalContentInstance.getParts).subscribe((data: any) => {
                if (data.items.length == 0) {
                  this.showToast('warn', '提示', '所选工单或工序暂无可退物料')
                }
                console.log(data.items)
                this.CreateJobOrderReturn.jobOrderReturnDetails = data.items
                this.CreateJobOrderReturn.jobOrderReturnDetails = this.CreateJobOrderReturn.jobOrderReturnDetails.map((item: any) => ({
                  jobOrderReturnDetailId: 0,
                  jobOrderReturnId: 0,
                  jobOrderId: item.jobOrderId,
                  jobNum: item.jobOrderNum,
                  processNumber: item.processNumber,
                  processId: item.processId,
                  jobOrderProcessId: item.jobOrderProcessId,
                  processNum: item.processNum,
                  processName: item.processName,
                  jobOrderProcessPartId: item.jobOrderProcessPartId,
                  partId: item.partId,
                  partNum: item.partNum,
                  partName: item.partName,
                  partType: item.partType || "",
                  partUOM: item.unit,
                  returnQuantity: 0,
                  returnUnit: item.unit,
                  returnWarehouseId: item.defaultWarehouseId,
                  warehouseNum:  item.defaultWarehouseNum,
                  warehouseName: item.defaultWarehouseName,
                  returnPositionId:item.defaultPositionId ,
                  positionNum: item.defaultPositionNum,
                  positionName: item.defaultPositionName,
                  requirementQuantity: item.requirementQuantity,
                  defaultWarehouseId: item.defaultWarehouseId,
                  defaultWarehouseName: item.defaultWarehouseName,
                  defaultWarehouseNum: item.defaultWarehouseNum,
                  defaultPositionId: item.defaultPositionId,
                  defaultPositionName: item.defaultPositionName,
                  defaultPositionNum: item.defaultPositionNum,
                  stockQuantity: item.stockQuantity,
                  issueQuantity: item.issuedQuantity,
                  status:item.status
                })
              )
              })
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectPart(dialogtype?: string) {
    const results = this.dialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width: '1000px',
      title: '选择物料',
      data: '生产退料单',
      content: GetPartsComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {

              this.CreateJobOrderReturn.jobOrderReturnDetails = results.modalContentInstance.selectData
              this.CreateJobOrderReturn.jobOrderReturnDetails = this.CreateJobOrderReturn.jobOrderReturnDetails.map((item: any) => ({
                jobOrderReturnDetailId: 0,
                jobOrderReturnId: 0,
                jobOrderId: item.jobOrderId,
                jobNum: item.jobOrderNum,
                processNumber: item.processNumber,
                processId: item.processId,
                jobOrderProcessId: item.jobOrderProcessId,
                processNum: item.processNum,
                processName: item.processName,
                jobOrderProcessPartId: item.jobOrderProcessPartId,
                partId: item.partId,
                partNum: item.partNum,
                partName: item.partName,
                partType: item.partType,
                partUOM: item.partUOM,
                returnQuantity: 0,
                returnUnit: item.partUOM,
                returnWarehouseId: item.defaultWarehouseId,
                warehouseNum:  item.defaultWarehouseNum,
                warehouseName: item.defaultWarehouseName,
                returnPositionId:item.defaultPositionId ,
                positionNum: item.defaultPositionNum,
                positionName: item.defaultPositionName,
                requirementQuantity: item.requirementQuantity,
                defaultWarehouseId: item.defaultWarehouseId,
                defaultWarehouseName: item.defaultWarehouseName,
                defaultWarehouseNum: item.defaultWarehouseNum,
                defaultPositionId: item.defaultPositionId,
                defaultPositionName: item.defaultPositionName,
                defaultPositionNum: item.defaultPositionNum,
                stockQuantity: item.stockQuantity,
                issueQuantity: item.issuedQuantity,
                status:item.status
              }))
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  SelectStorehouse(rowItem: any, dialogService?: string) {
    const results = this.dialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width: '1000px',
      title: '选择仓库',
      data: rowItem,
      content: SelectStorehouseComponent,
      dialogtype: dialogService,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {
              rowItem.warehouseName = results.modalContentInstance.selectData.warehouseName;
              rowItem.warehouseNum = results.modalContentInstance.selectData.warehouseNum;
              rowItem.returnWarehouseId = results.modalContentInstance.selectData.warehouseId;
              rowItem.defaultWarehouseId = results.modalContentInstance.selectData.warehouseId;
              rowItem.defaultWarehouseName = results.modalContentInstance.selectData.warehouseName;
              rowItem.defaultWarehouseNum = results.modalContentInstance.selectData.warehouseNum;
              rowItem.defaultPositionId = null,
              rowItem.defaultPositionName = null,
              rowItem.defaultPositionNum = null,
              rowItem.positionName = null,
              rowItem.positionNum = null,
              rowItem.returnPositionId = null
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectPosition(rowItem: any, dialogService?: string) {
    if(rowItem.returnWarehouseId){
      const results = this.dialogService.open({
        id: 'dialog-service',
        showAnimation: true,
        width: '1000px',
        title: '选择库位',
        data: {
          warehouseId: rowItem.returnWarehouseId,
        },
        content: SelectPositionComponent,
        dialogtype: dialogService,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'primary',
            text: '确定',
            disabled: false,
            handler: ($event: Event) => {
              if (results.modalContentInstance.selectData) {
                rowItem.positionName = results.modalContentInstance.selectData.positionName;
                rowItem.positionNum = results.modalContentInstance.selectData.positionNum;
                rowItem.returnPositionId = results.modalContentInstance.selectData.positionId;
                rowItem.defaultPositionId = results.modalContentInstance.selectData.positionId;
                rowItem.defaultPositionName = results.modalContentInstance.selectData.positionName;
                rowItem.defaultPositionNum = results.modalContentInstance.selectData.positionNum;
              }
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }else{
      this.showToast('error', '失败', '请先选择仓库')
    }
  }
  delete(index: number, dialogtype?: string) {
    const results = this.dialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width: '400px',
      title: '删除',
      content: '确认删除该条数据吗？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            this.CreateJobOrderReturn.jobOrderReturnDetails.splice(index, 1)
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }
  apart(index: number) {
    const item = JSON.parse(JSON.stringify(this.CreateJobOrderReturn.jobOrderReturnDetails[index])); // 获取索引位置的元素的深拷贝
    item.PreIssuedQuantity = 0; // 将 PreIssuedQuantity 设置为 0
    this.CreateJobOrderReturn.jobOrderReturnDetails.splice(index + 1, 0, item); // 将修改后的 item 插入到数组中
  }

  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
}
